package utils;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import utils.titles.Title;

import java.util.prefs.Preferences;

/**
 * Created by thormentor on 19-05-2014.
 */
public class Base {
    private Title title;
    private transient Title.TitleFormatter formatter;
    private Preferences preferences;

    public Base(Title.TitleFormatter formatter) {
        this.formatter = formatter;
        this.title = Title.fromObject(this);
    }

    public Base(Title.TitleFormatter formatter, Title title) {
        this.formatter = formatter;
        this.title = title;
    }

    public Base(Title.TitleFormatter formatter, String name) {
        this.formatter = formatter;
        this.title = formatter.parse(name);
    }

    @Override
    public String toString() {
        return getName();
    }

    public String getName() {
        return formatter.format(title);
    }

    public void setTitle(Title title) {
        this.title = title;
    }

    public Title getTitle() {
        return title;
    }

    protected void singularize() {
        setTitle(getTitle().getSingularized());
    }

    protected void pluralize() {
        setTitle(getTitle().getPluralized());
    }

    public void save(String key, Object o) {
        getPreferences().put(key, Utils.getGson().toJson(o));
    }

    private Preferences getPreferences() {
        if (preferences == null)
            preferences = Preferences.userNodeForPackage(getClass());

        return preferences;
    }

    public <K> ObservableList<K> getObservableList(String key, Class<K[]> aClass) {
        return FXCollections.observableArrayList(Utils.getGson().fromJson(getPreferences().get(key, "[]"), aClass));
    }
}
